package com.atguigu.web;

import com.atguigu.dao.BookDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.pojo.Cart;
import com.atguigu.pojo.Order;
import com.atguigu.pojo.OrderItem;
import com.atguigu.pojo.User;
import com.atguigu.service.impl.OrderServiceImpl;
import com.atguigu.utils.JdbcUtils;
import com.atguigu.utils.WebUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class OrderServlet extends BaseServlet {
    OrderServiceImpl orderService=new OrderServiceImpl();
    protected void createOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("OrderServlet程序在["+Thread.currentThread().getName()+"]线程中");
        if(request.getSession().getAttribute("user")!=null){
            String orderId=orderService.createOrder(
                    (Cart)request.getSession().getAttribute("cart"),
                    ((User)request.getSession().getAttribute("user")).getId()
            );
            //try {//这里写try catch的原因是:BaseDao类里在执行sql时,抛出了异常,我们在这里要处理这个异常,建订单,变删订单.
            //    orderId = orderService.createOrder((Cart)request.getSession().getAttribute("cart"), ((User)request.getSession().getAttribute("user")).getId());
            //    JdbcUtils.commitAndClose();//没有异常就提交事务,关闭mysql连接
            //} catch (Exception e) {
            //    JdbcUtils.rollbackAndClose();//如果有异常,就要回滚事务,并关闭mysql连接
            //    e.printStackTrace();
            //}//这里注释,是因为写了 TransacationFile 过滤器,在那个上层调用者身上接受异常,执行回滚操作或没有异常执行提交操作
            request.getSession().setAttribute("orderId",orderId);
            response.sendRedirect("pages/cart/checkout.jsp");
        }else{
            request.getRequestDispatcher("pages/user/login.jsp");
            return;
        }
    }

    protected void showMyOrders(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Order> orderList=orderService.showMyOrders(((User)(request.getSession().getAttribute("user"))).getId());
        request.getSession().setAttribute("orderList",orderList);
        response.sendRedirect("pages/order/order.jsp");
    }
    protected void showOrderDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<OrderItem> orderItems=orderService.showOrderDetail(request.getParameter("orderId"));
        request.getSession().setAttribute("orderItems",orderItems);
        response.sendRedirect("pages/order/order.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
